package org.clever.arkdemo.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MysqlConnection implements AutoCloseable {

    private static boolean isInit = false;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            isInit = true;
        } catch (ClassNotFoundException e) { }
    }

    private Connection connection;
    // jdbc:mysql://rm-2ze6v0919s94r4fem1o.mysql.rds.aliyuncs.com
    public MysqlConnection(String url, String username, String password) throws SQLException {
        if (!isInit) {
            throw new RuntimeException("mysql driver not init");
        }
        connection = DriverManager.getConnection(url, username, password);
    }

    /**
     * 设置为手动提交事务
     */
    public void unAutoCommit() throws SQLException {
        connection.setAutoCommit(false);
    }

    public void commit() throws SQLException {
        connection.commit();
    }

    public void rollback() throws SQLException {
        connection.rollback();
    }

    @Override
    public void close() throws SQLException {
        if (connection != null) {
            connection.close();
        }
        connection = null;
    }

    public Connection getConnection() {
        return connection;
    }
}
